package edu.hawaii.halealohacli.command;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.client.BadXmlException;
import org.wattdepot.client.MiscClientException;
import org.wattdepot.client.NotAuthorizedException;
import org.wattdepot.client.ResourceNotFoundException;
import org.wattdepot.client.WattDepotClient;
import org.wattdepot.resource.source.jaxb.Source;

/**
 * Defines the daily-energy command for hale-aloha-cli-chair.
 * 
 * @author Chris Fang
 */
public class DailyEnergy implements Command {

  private WattDepotClient client;
  private String name;
  private String usage;
  private String description;
  private SourceData dataModule;
  private String nameFromUser;
  private String dateFromUser;
  private String errorMsg;

  /**
   * Creates an instance of this command with the client set to null by default, requiring
   * initialization.
   */
  public DailyEnergy() {
    this.name = "daily-energy";
    this.usage = "daily-energy [tower | lounge] [date]";
    this.description =
        "Returns the energy in kWh used by the tower or lounge for the specified date (yyyy-mm-dd)";
    this.errorMsg = "The date %s is invalid " + "(Enter \"help\" to see command usage)";
  }

  /**
   * Initializes this command with a healthy WattDepot client.
   * 
   * @param client A healthy WattDepot client used to initialize the command
   * @param args Arguments required by the command for execution
   * @return Whether or not the arguments passed was accepted by the command initialization
   */
  @Override
  public boolean initializeCommand(WattDepotClient client, String[] args) {
    this.client = client;
    if (args.length != 3) {
      System.out.format("The arguments are invalid " + "(Enter \"help\" to see command usage)");
      return false;
    }
    this.nameFromUser = args[1];
    this.dateFromUser = args[2];
    return true;
  }

  /**
   * Returns the name of this command.
   * 
   * @return the name of this command
   */
  @Override
  public String getName() {
    return this.name;
  }

  /**
   * Returns the usage syntax of this command.
   * 
   * @return the usage syntax of this command
   */
  @Override
  public String getUsage() {
    return this.usage;
  }

  /**
   * Returns the description of this command.
   * 
   * @return a description of this command
   */
  @Override
  public String getDescription() {
    return this.description;
  }

  /**
   * Initialize the SouceData with the energy data obtained from the client.
   * 
   * @param name The name of the tower or lounge to get data from
   * @param date The date from which the energy data should be from
   * @return Whether or not the data was successfully initialized
   */
  public boolean initializeData(String name, String date) {
    try {
      Source source = client.getSource(name);
      Calendar startTime = getStartTime(date);
      if (startTime == null) {
        System.out.format(errorMsg, date);
        return false;
      }
      Calendar endTime = (Calendar) startTime.clone();
      endTime.add(Calendar.HOUR, 24);
      dataModule = new SourceData(source.getName());
      dataModule.setEnergyConsumed(client.getEnergyConsumed(source.getName(),
          toXMLGregorianCalendar(startTime), toXMLGregorianCalendar(endTime), 15));
      return true;
    }
    catch (NotAuthorizedException e) {
      System.out.format("You are not authorized to view %s", name);
      return false;
    }
    catch (ResourceNotFoundException e) {
      System.out.format("The tower or lounge %s is invalid "
          + "(Enter \"help\" to see available sources", name);
      return false;
    }
    catch (BadXmlException e) {
      System.out.format("Bad XML: %s", e.getMessage());
      return false;
    }
    catch (MiscClientException e) {
      System.out.format("Unknown error has occurred: %s", e.getMessage());
      return false;
    }
  }

  /**
   * Try to convert a String representation of a date into a Calendar representation.
   * 
   * @param date String representation of a date
   * @return A Calendar representation for the input date or NULL if the date was invalid
   */
  protected Calendar getStartTime(String date) {
    Calendar inputDate = GregorianCalendar.getInstance();
    Calendar today = GregorianCalendar.getInstance();
    Date convertedDate = convertDate(date);
    if (convertedDate == null) {
      return null;
    }
    inputDate.setTime(convertedDate);
    if (inputDate.compareTo(today) <= 0) {
      return inputDate;
    }
    else {
      return null;
    }
  }

  /**
   * Try to convert a String representation into a Date object.
   * 
   * @param date String representation of a date
   * @return A Date object for the input date or NULL if the conversion was unsuccessful
   */
  protected Date convertDate(String date) {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
    try {
      Date parsedDate = formatter.parse(date);
      if (!formatter.format(parsedDate).equals(date)) {
        System.out.format(errorMsg, date);
        return null;
      }
      return parsedDate;

    }
    catch (Exception e) {
      System.out.format(errorMsg, date);
      return null;
    }
  }

  /**
   * Prints the results of executing this command.
   */
  @Override
  public void printResults() {
    if (!initializeData(this.nameFromUser, this.dateFromUser)) {
      return;
    }
    System.out.format("%s's energy consumption for %s was: %.1f kWh.", dataModule.getName(),
        this.dateFromUser, dataModule.getEnergyConsumed() / 1000);
  }

  /**
   * Converts a calendar object into a XMLGregorianCalendar object.
   * 
   * @param date The Calendar object to be converted
   * @return The converted XMLGregorianCalendar object
   */
  protected XMLGregorianCalendar toXMLGregorianCalendar(Calendar date) {
    GregorianCalendar calendar = (GregorianCalendar) date;
    try {
      DatatypeFactory converter = DatatypeFactory.newInstance();
      return converter.newXMLGregorianCalendar(calendar);
    }
    catch (DatatypeConfigurationException e) {
      System.out.format("There was a problem in the date conversion: " + e.getMessage());
      return null;
    }
  }

}
